package cn.gson.school.controller.jiaoxue;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.*;

import cn.gson.school.dao.jiaoxue.AnswerDao;
import cn.gson.school.dao.jiaoxue.GrandeDao;
import cn.gson.school.dao.jiaoxue.ScoreDao;
import cn.gson.school.dao.jiaoxue.StudentDao;
import cn.gson.school.dao.jiaoxue.ZhangJieDao;
import cn.gson.school.dao.jiaoxue.ZuoYeClassDao;
import cn.gson.school.dao.jiaoxue.ZuoYeDao;
import cn.gson.school.dao.jiaoxue.ZuoYeTitleDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.entity.jiaoxue.*;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.mappers.jiaoxue.AnswerMappers;
import cn.gson.school.mappers.jiaoxue.ZuoYeMappers;
import cn.gson.school.service.jiaoxue.ZuoYeService;

@Controller
@RequestMapping("/zuoye")
public class ZuoYeController {

	@Autowired
	private ZuoYeMappers zuoyeMappers;

	@Autowired
	private ZuoYeDao zuoyeDao;

	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	private Random random = new Random();

	@Autowired
	private ZhangJieDao zhangjieDao;

	@Autowired
	private UserInfoDao userinfoDao;

	@Autowired
	private ZuoYeTitleDao zuoyeTitleDao;

	@Autowired
	private ZuoYeClassDao zuoyeClassDao;

	@Autowired
	private ZuoYeService zuoyeService;

	@Autowired
	private StudentDao studentDao;

	@Autowired
	private GrandeDao grandeDao;

	@Autowired
	private AnswerMappers answerMappers;

	@Autowired
	private AnswerDao answerDao;
	
	@Autowired
	private ScoreDao scoreDao;

	// 查询所有班级
	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> index(
			ZuoYeEntity zuoyeEntity,
			@RequestParam(name = "page", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "rows", defaultValue = "20") Integer pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		System.out.println("zuoyeEntity:" + zuoyeEntity);
		List<ZuoYeEntity> list = zuoyeMappers.zuoyeList(zuoyeEntity);
		PageInfo<ZuoYeEntity> info = new PageInfo<>(list);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	// 前台学生保存作业的答案
	@GetMapping("savezuoye/{titleId}/{studentId}/{zuoyeId}/{answer}")
	@ResponseBody
	public Map<String, Object> saveZuoYe(
			@PathVariable(name = "titleId") Long titleId,
			@PathVariable(name = "studentId") Long studentId,
			@PathVariable(name = "zuoyeId") Long zuoyeId,
			@PathVariable(name = "answer") String answer) {
		System.out.println("进来了。。。DDD");
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
			AnswerEntity answerEntitys = answerMappers.cxAnswer(studentId, titleId, zuoyeId);
			System.out.println("answerEntitys" + answerEntitys);
			if (answerEntitys != null) {
				System.out.println("进来了。。。修改");
				answerEntitys.setAnswer(answer);
				System.out.println("SSS:" + answerEntitys);
				answerDao.save(answerEntitys);
				obj.put("success", true);
			} else {
				System.out.println("进来了。。。添加");
				AnswerEntity daAn = new AnswerEntity();
				daAn = new AnswerEntity();
				daAn.setDelete(1);
				daAn.setState("未提交");
				daAn.setAnswer(answer);
				daAn.setTime(new Date());
				daAn.setStudentId(studentId);
				daAn.setTitleId(titleId);
				daAn.setZuoYeId(zuoyeId);
				answerDao.save(daAn);
			}
		return obj;
	}
	// 前台学生提交作业的答案
		@GetMapping("/jiaozuoye/{titleId}/{studentId}/{zuoyeId}/{answer}")
		@ResponseBody
		public Map<String, Object> jiaoZuoYe(
				@PathVariable(name = "titleId") Long titleId,
				@PathVariable(name = "studentId") Long studentId,
				@PathVariable(name = "zuoyeId") Long zuoyeId,
				@PathVariable(name = "answer") String answer) {
			System.out.println("进来了。。。EEE");
			Map<String, Object> obj = new HashMap<String, Object>();
			obj.put("success", false);
				AnswerEntity answerEntitys = answerMappers.cxAnswer(studentId, titleId, zuoyeId);
				if (answerEntitys != null) {
					answerEntitys.setAnswer(answer);
					answerEntitys.setState("已提交");
					answerDao.save(answerEntitys);
					obj.put("success", true);
				} else {
					AnswerEntity daAn = new AnswerEntity();
					daAn = new AnswerEntity();
					daAn.setDelete(1);
					daAn.setState("已提交");
					daAn.setAnswer(answer);
					daAn.setTime(new Date());
					daAn.setStudentId(studentId);
					daAn.setTitleId(titleId);
					daAn.setZuoYeId(zuoyeId);
					answerDao.save(daAn);
				}
			return obj;
		}

		

		// 后台提交作业
		@GetMapping("/yuejuan/{zuoyeId}/{studentId}")
		@ResponseBody
		public Map<String, Object> cx(
				@PathVariable(name = "zuoyeId") Long zuoyeId,
				@PathVariable(name = "studentId") Long studentId) {
			Map<String, Object> obj = yuejuan(zuoyeId, studentId, "无");
			obj.put("success", true);
			return obj;

		}
	
		
	// 后台提交作业
	@GetMapping("/yuejuan/{zuoyeId}/{studentId}/{appriase}")
	@ResponseBody
	public Map<String, Object> yuejuan(
			@PathVariable(name = "zuoyeId") Long zuoyeId,
			@PathVariable(name = "studentId") Long studentId,
			@PathVariable(name = "appriase", required = false) String appriase) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Integer sum=0;
		List<AnswerEntity> answerEntitys=answerDao.findByStudentIdAndZuoYeId(studentId, zuoyeId);
		for (AnswerEntity answerEntity : answerEntitys) {
			System.out.println(answerEntity.getScore());
			sum +=answerEntity.getScore();
		}
		System.out.println("分数："+sum);
		GradeEntity gradeEntitys = grandeDao.cxGrande(zuoyeId, studentId);
		if (gradeEntitys == null) {
			// 添加分数到学生作业成绩表中
			gradeEntitys = new GradeEntity();
		} else {
			gradeEntitys.setGradeId(gradeEntitys.getGradeId());
		}
		ZuoYeEntity zuoYeEntity = zuoyeDao.findOne(zuoyeId);
		StudentEntity studentEntity = studentDao.findOne(studentId);
		gradeEntitys.setStudentinfoId(studentEntity);
		gradeEntitys.setZuoye(zuoYeEntity);
		gradeEntitys.setDelete(1);
		System.out.println("appriase" + appriase);
		if (appriase == null || "无".equals(appriase)) {
			gradeEntitys.setApprise("");
		} else {
			gradeEntitys.setApprise(appriase);
		}
		gradeEntitys.setSumScore(Double.valueOf(sum.toString()));
		grandeDao.save(gradeEntitys);
		OreditEntity oreditEntity=new OreditEntity();
		oreditEntity.setOperatingTime(new Date());//设置操作的时间
		oreditEntity.setDelete(1);
		oreditEntity.setOperationReason("提交了一份练习");
		oreditEntity.setOperationScore(5);
		oreditEntity.setStudent(studentEntity);
		oreditEntity.setCreditTableId(studentEntity.getTotalCredits()+5);
		scoreDao.save(oreditEntity);
		studentEntity.setTotalCredits(studentEntity.getTotalCredits()+5);
		studentDao.save(studentEntity);
		obj.put("success", true);
		return obj;
	}
	
	//布置作业
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public Map<String, Object> save(
			@Valid ZuoYeEntity zuoYeEntity, 
			BindingResult br, 
			HttpServletRequest request,
			Model model) throws ParseException {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		String userinfo = request.getParameter("userinfo");// 操作人
		String user = request.getParameter("user");// 出卷人
		String phase = request.getParameter("phase");// 阶段
		String chapter = request.getParameter("chapter");// 章节
		String buZhiTime = request.getParameter("buzhiTime");// 布置时间
		String endTime = request.getParameter("endTime");// 结束时间
		String youXiaoTime = request.getParameter("youXiaoTime");// 作业有效时间
		String XuanZeCount = request.getParameter("optionCount");// 获取选择题的数量
		String panDuanCount = request.getParameter("panDuanCount");// 获取判断题的数量
		String daiMaCount = request.getParameter("daiMaCount");// 获取代码题的数量
		String selectClass = request.getParameter("selectedClass");// 获取选择题的数量
		UserInfoEntity userInfoEntity = userinfoDao.findOne(Long.valueOf(userinfo));
		ZuoYeEntity zuoYe;
		// 往作业表中添加数据
		if (zuoYeEntity.getZuoyeId() == null) {
			zuoYe = new ZuoYeEntity();
			zuoYe.setBuzhiTime(df.parse(buZhiTime));// 添加布置的时间
			zuoYe.setUserinfo(userInfoEntity);// 设置布置作业的老师
			zuoYe.setAddPlus(zuoYeEntity.getAddPlus());// 添加备注
			zuoYe.setZuoyeName(zuoYeEntity.getZuoyeName());// 设置作业的名称
			zuoYe.setEndTime(df.parse(endTime));// 添加结束的时间
			zuoYe.setOptionCount(zuoYeEntity.getOptionCount());// 添加选择题数量
			zuoYe.setPanDuanCount(zuoYeEntity.getPanDuanCount());// 添加判断题数量
			zuoYe.setDaiMaCount(zuoYeEntity.getDaiMaCount());// 添加代码题数量
			zuoYe.setDelete(1);// 设置是否删除
			zuoYe.setType(zuoYeEntity.getType());// 设置作业类型
			zuoYe.setYouXiaoTime(youXiaoTime);// 获取考试的有效时间
			zuoYe.setZuoyeState("已布置");// 设置作业的状态
			// 添加章节编号
			// 根据阶段编号、章节名称获取所有的章节
			
			ChapterEntity chapterEntity =
					zhangjieDao.findByChapterNameAndPhaseId(chapter, Long.valueOf(phase));
			
			zuoYe.setChapterinfo(chapterEntity.getChapterId());
			zuoyeDao.save(zuoYe);// 添加作业表
			
			ZuoYeEntity zuoYeEntity2 = 
					zuoyeDao.findByZuoyeName(zuoYeEntity.getZuoyeName());
			
			zuoyeService.index2(XuanZeCount, "选择题", zuoYeEntity2.getZuoyeId(), chapterEntity.getChapterId());
			zuoyeService.index2(panDuanCount, "判断题", zuoYeEntity2.getZuoyeId(), chapterEntity.getChapterId());
			zuoyeService.index2(daiMaCount, "代码题", zuoYeEntity2.getZuoyeId(), chapterEntity.getChapterId());
			// 获取布置作业的班级*******************
			String[] x = selectClass.split(",");
			for (int i = 0; i < x.length; i++) {
				Long y = Long.parseLong(x[i].trim());
				ZuoYeClassEntity zuoYeClassEntity = new ZuoYeClassEntity();
				zuoYeClassEntity.setZuoyeId(zuoYeEntity2.getZuoyeId());
				zuoYeClassEntity.setClassId(y);
				zuoYeClassEntity.setState("未批阅");
				zuoyeClassDao.save(zuoYeClassEntity);
			}
		} else {
			System.out.println("编辑");
			zuoYe = zuoyeDao.findOne(zuoYeEntity.getZuoyeId());
			zuoYe.setZuoyeId(zuoYeEntity.getZuoyeId());// 设置作业编号
			zuoYe.setUserinfo(userInfoEntity);// 设置布置作业的老师
			zuoYe.setAddPlus(zuoYeEntity.getAddPlus());// 添加备注
			zuoYe.setZuoyeName(zuoYeEntity.getZuoyeName());// 设置作业的名称
			zuoYe.setEndTime(df.parse(endTime));// 添加结束的时间
			zuoYe.setOptionCount(zuoYeEntity.getOptionCount());// 添加选择题数量
			zuoYe.setPanDuanCount(zuoYeEntity.getPanDuanCount());// 添加判断题数量
			zuoYe.setDaiMaCount(zuoYeEntity.getDaiMaCount());// 添加代码题数量
			zuoYe.setDelete(1);// 设置是否删除
			zuoYe.setType(zuoYeEntity.getType());// 设置作业类型
			zuoYe.setYouXiaoTime(youXiaoTime);// 获取考试的有效时间
			zuoYe.setZuoyeState("已布置");// 设置作业的状态
			// 添加章节编号
			// 根据阶段编号、章节名称获取所有的章节
			ChapterEntity chapterEntity = zhangjieDao.findByChapterNameAndPhaseId(chapter, Long.valueOf(phase));
			zuoYe.setChapterinfo(chapterEntity.getChapterId());
			zuoyeDao.save(zuoYe);// 添加作业表
			zuoyeService.index(XuanZeCount, zuoYeEntity.getZuoyeId(), "选择题", chapterEntity.getChapterId());// 修改选择题
			zuoyeService.index(panDuanCount, zuoYeEntity.getZuoyeId(), "判断题", chapterEntity.getChapterId());// 修改选择题
			zuoyeService.index(daiMaCount, zuoYeEntity.getZuoyeId(), "代码题", chapterEntity.getChapterId());// 修改选择题

		}
		obj.put("success", true);
		return obj;
	}
	
	// 后台添加老师阅卷的题目分数（保存）
		@GetMapping("/addscore/{titleId}/{studentId}/{score}/{zuoyeId}/{userinfo}")
		@ResponseBody
		public Map<String, Object> addScore(
				@PathVariable(name = "titleId") Long titleId,
				@PathVariable(name = "studentId") Long studentId,
				@PathVariable(name = "score") Integer score,
				@PathVariable(name = "zuoyeId", required = false) Long zuoyeId,
				@PathVariable(name = "userinfo") Long userinfo) {
			Map<String, Object> obj = new HashMap<String, Object>();
			obj.put("success", false);
			/*System.out.println("titleId"+titleId);
			System.out.println("studentId"+studentId);
			System.out.println("score"+score);
			System.out.println("zuoyeId"+zuoyeId);*/
			AnswerEntity answerEntitys = answerMappers.cxAnswer(studentId, titleId, zuoyeId);
			System.out.println("answerEntitys"+answerEntitys);
			answerEntitys.setScore(score);
			answerEntitys.setUserinfoId(userinfo);
			answerDao.save(answerEntitys);
			obj.put("success", true);
			return obj;
		}
}
